#!/bin/bash
# This is a shell version
# And 'jq' and 'curl' are inneed: apt install jq curl -y
# You must be sure every file has been setten and all correct!
getAccessToken() {
    # Get user configs
    user_conf_json=`cat wecom.conf`
    corpid=`echo $user_conf_json | jq -r '.corpid'`
    corpsecret=`echo $user_conf_json | jq -r '.corpsecret'`
    # Get AccessToken
    access_json=`curl -s -G -d "corpid=${corpid}" -d "corpsecret=${corpsecret}" https://qyapi.weixin.qq.com/cgi-bin/gettoken`
    # access_json=`curl -s -G -d "corpid=12334" -d "corpsecret=${corpsecret}" https://qyapi.weixin.qq.com/cgi-bin/gettoken`
    errorCode=`echo $access_json | jq '.errcode'`
    if [ $errorCode -eq 0 ]; then
        # echo "Get accessCode success"
        accessToken=`echo $access_json | jq -r '.access_token'`
        echo $accessToken
        return 0
    else
        errorMsg=`echo $access_json | jq -r '.errmsg'`
        echo "Get accessCode failed, errorCode is "$errorCode", errorMsg: "$errorMsg
        return -1
    fi
}

sendMsg() {
    # Get AgentId=
    user_conf_json=`cat wecom.conf`
    AgentId=`echo $user_conf_json | jq -r '.AgentId'`
    msg="${@:2}"
    # curl -s -o /dev/null -X POST -H "Content-Type: application/json" -d "{\"touser\": \"@all\", \"msgtype\": \"text\", \"agentid\": \"1000002\", \"text\": {\"content\": \"$msg\"}, \"safe\": 0}" https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$1
    send_json=`curl -s -X POST -H "Content-Type: application/json" -d "{\"touser\": \"@all\", \"msgtype\": \"text\", \"agentid\": \"1000002\", \"text\": {\"content\": \"$msg\"}, \"safe\": 0}" https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$1`
    if [ $? -ne 0 ]; then
        echo "Send error"
    else
        errorCode=`echo $send_json | jq '.errcode'`
        if [ $errorCode -eq 0 ]; then
            echo "Send success"
        else
            errorMsg=`echo $send_json | jq -r '.errmsg'`
            echo "Send error, error message: $errorMsg [$errorCode]"
        fi
    fi
}

# Check curl
curl bing.com
if [ $? -ne 0 ]; then
	echo "You musy install curl first, in debian, run: apt install curl -y"
	exit
fi
# Check jq
echo '{"foo": 0}' | jq . > /dev/null
if [ $? -ne 0 ]; then
    echo "You must install jq first, in debian, run: apt install jq -y"
    exit
fi

# Check config file exists
if [ -f wecom.conf ]; then
    if [ $# -lt 1 ]; then
        echo "You must input message you wanna to send, eg:"
        echo "bash wecom.sh Hello"
    else
        accessToken=`getAccessToken`
        if [ $? -eq 0 ]; then
            sendMsg $accessToken "$*"
            # echo "$*"
        fi
    fi
else
    echo "Creating sample config file"
    echo '{
    "corpid": "wwabcddzxdkrsdv",
    "corpsecret": "vQT_03RDVA3uE6JDASDASDAiXUvccqV8mDgLdLI",
    "AgentId": 1000002,
    "dataRecord": 1' > wecom.conf
    echo "}" >> wecom.conf
fi



